/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package entity;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

/**
 *
 * @author artha
 */


public class KelolaObat {
    public KelolaObat() {
        emf = Persistence.createEntityManagerFactory("Dokter_mandiriPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void createObat(Obat obat) {
        EntityManager em = getEntityManager();
        em.getTransaction().begin();
        try {
            em.persist(obat);
            em.getTransaction().commit();
        } catch (Exception e) {
            em.getTransaction().rollback();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }
    public Obat getObat(String username) {
        Obat obat = null;
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("SELECT object(a) FROM Obat AS a WHERE a.username=:usr");
            q.setParameter("usr", username);
            obat = (Obat) q.getSingleResult();
        } finally {
            if (em != null) {
                em.close();
            }
        }
        return obat;
    }
    public boolean checkObat(String username) {
        boolean result = false;
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("SELECT count(o) FROM Obat AS o WHERE o.username=:usr");
            q.setParameter("usr", username);
            int jumlahUser = ((Long) q.getSingleResult()).intValue();
            if (jumlahUser > 0) {
                result = true;
            }
        } finally {
            if (em != null) {
                em.close();
            }
        }
        return result;
    }
    public void createPromotor(Obat obat) {
        EntityManager em = getEntityManager();
        em.getTransaction().begin();
        try {
            em.persist(obat);
            em.getTransaction().commit();
        } catch (Exception e) {
            em.getTransaction().rollback();
        } finally {
            if (em != null) {
                em.close();
            }
        }


    
}
}
